package com.cmw.auntapp.presenter;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.constant.API;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.core.base.BasePresenter;
import com.cmw.auntapp.core.base.IBaseView;
import com.cmw.auntapp.core.base.vo.AppVersionResult;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.AppTools;
import com.cmw.auntapp.core.util.CommonUtil;
import com.cmw.auntapp.core.util.DownloadUtil;
import com.cmw.auntapp.core.util.EnvironmentShare;
import com.cmw.auntapp.core.util.HttpUtil;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.core.util.ShellUtils;
import com.cmw.auntapp.core.util.StringHandler;
import com.cmw.auntapp.core.util.StringUtils;
import com.cmw.auntapp.core.util.ToastAlert;
import com.cmw.auntapp.core.util.ValidUtil;
import com.cmw.auntapp.model.UserModel;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.cmw.auntapp.constant.Constant.HANDLER_APK_DOWNLOAD_PROGRESS;
import static com.cmw.auntapp.constant.Constant.SHOW_LOADING_KEY;
import static com.cmw.auntapp.constant.Constant.SHOW_LOADING_YES;
import static com.cmw.auntapp.constant.Constant.USER_INEMPID_KEY;
import static com.cmw.auntapp.constant.Constant.USER_MEMBERID_KEY;
import static com.cmw.auntapp.constant.Constant.USER_RNAME_KEY;
import static com.cmw.auntapp.constant.Constant.USER_USERAUTHTOKEN_KEY;

/**
 * @desc: 首页业务类
 * @author: chengmingwei
 * @date: 2021/4/28 20:31
 * @contact: phone(微信同号):13922111489 / email: 340360491@qq.com
 */
public class MainPresenter extends BasePresenter<UserModel> {
    private IBaseView iBaseView;

    public MainPresenter(IBaseView iBaseView) {
        this.iBaseView = iBaseView;
        init();
    }


    /**
     *  获取阿姨待抢订单数量
     */
    public void getOrderCount() {
        Map<String, String> params = new HashMap<>();
        params.put(SHOW_LOADING_KEY, SHOW_LOADING_YES);
        get(API.ORDER_AUNT_COUNT, CommandType.GET, params);
    }

    /**
     * App 更新检测
     */
    public void checkUpdate(){
        Context mContext = getContext();
        String version = AppTools.getVersionCode(mContext) + "";
        String versionName = AppTools.getVerName(mContext);
        String packageName = getContext().getPackageName();
        Log.e(TAG, "versionName="+versionName+", versionCode="+version+", packageName="+packageName);
        Map<String, String> params = new HashMap<String, String>();
        params.put("version", version);
        params.put("packageName",packageName);
        params.put(SHOW_LOADING_KEY, SHOW_LOADING_YES);
        get(API.APPUP_UPDATE_CHECK, CommandType.CHECK_APP_UPDATE, params);
    }


    public void downloadAPK(AppVersionResult appVersionResult, final Handler handler) {
        DownloadUtil util = DownloadUtil.get();
        Integer utype = appVersionResult.getUtype();  //更新方式 1:静默更新,2:手动更新
        String appPath = appVersionResult.getAppPath();
        String _savePath = null;
        //final String savePath = "/mnt/sdcard/com.yf.cmw/";

        String apkName = null;
        apkName = StringHandler.formatStr("%s.apk", AppTools.getAppName(getContext()));
        _savePath = EnvironmentShare.APK + "/";
        final String savePath = _savePath;
        util.download(appPath, savePath, apkName, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                installAndOpen(file, savePath);
            }

            @Override
            public void onDownloading(int progress) {
                Log.e(TAG, String.format("阿姨APP下载进度：%d", progress));
                Message message = new Message();
                message.what = HANDLER_APK_DOWNLOAD_PROGRESS;
                message.arg1 = progress;
                handler.sendMessage(message);
            }

            @Override
            public void onDownloadFailed(String errMsg) {
                Log.e(TAG, String.format("阿姨APP下载失败：%s", errMsg));
            }
        });
    }

    void installAndOpen(File file, String savePath) {
        ShellUtils.execCommand("chmod 777 " + savePath, false);
        String filePath = file.getAbsolutePath();
        if (!StringUtils.isEmpty(savePath)) {
            Context context = getContext();
            ToastAlert.init(context);
            CommonUtil.updateAPK(context, file);
            ToastAlert.showMsg("阿姨APP更新成功!");
        }
    }

    @Override
    protected IBaseView getView() {
        return iBaseView;
    }


}
